Create a form

  • in module.ts

    Step 1: import FormsModule, ReactiveFormsModule

    
                      import { FormsModule, ReactiveFormsModule } from '@angular/forms';
                      

    Step2: add FormsModule,ReactiveFormsModule into imports[]

    
                      imports: [ FormsModule,ReactiveFormsModule],
                      

  • in components

    Step1: import FormBuilder, FormGroup

    
                      import { FormBuilder, FormGroup } from '@angular/forms';
                      
    1) FormGroup will be used in the STEP 2 for variable declaration
    2) FormBuilder will be used in STEP 3 to inject into constroctor()

    Step2: declare formGroup variable

    
                      mainForm: FormGroup;
                      ...
                      .... 
                      constructor(){
    
                      }
                    

    Step3: inject 'FormBuilder' into constroctor()

    
                    constructor( private fb: FormBuilder,) {
    
                    }
                    

    Step4: define mainForm (FormGroup)

    
                    this.mainForm = this.fb.group({
                      'name': [''],
                      'symbol':[''],
                      'parent_id' :['']                  
            
                   });
                   
    1) mainForm will be used in the html inside the form tag
    2) name ,symbol and parent_id are formContol. These will be used for formControlName inside the form tag

  • in view page

    Step1: link the formGroup with form

    
                      <form [formGroup]="mainForm" (ngSubmit)="doSave()"></form>
                      

    Step2: link the formGroup elements inside the form tag

    Code

    
    
                      <form [formGroup]="mainForm" (ngSubmit)="doSave()">
                          <input type="text" class="form-control" formControlName="name" >
                          <input type="text" class="form-control" formControlName="symbol" >
                          <input type="text" class="form-control" formControlName="parent_id" >
                    </form>